<template>

<el-tabs
    v-model="editableTabsValue"
    type="card"
    class="demo-tabs"
    editable
    @edit="handleTabsEdit"
  >
    <template #add-icon>
      <el-icon><Select /></el-icon>
    </template>
    <el-tab-pane
      v-for="item in editableTabs"
      :key="item.name"
      :label="item.title"
      :name="item.name"
    >
    <el-button type="primary" @click="openDialog"><el-icon><Plus /></el-icon>&nbsp;新增 </el-button>

    <el-dialog  v-model="from.dialogFormVisible" title="基本信息" width="500" >
    <el-form :model="from">
      <el-form-item label="商品名称:" :label-width="formLabelWidth">
        <el-input v-model="from.shopName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="生产批次:" :label-width="formLabelWidth">
        <el-input v-model="from.batch" autocomplete="off" />
      </el-form-item>
      <el-form-item label="保质期（天）:" :label-width="formLabelWidth">
        <el-input v-model="from.expiration" autocomplete="off" />
      </el-form-item>
      <el-form-item label="生产许可证号:" :label-width="formLabelWidth">
        <el-input v-model="from.production_License" autocomplete="off" />
      </el-form-item>
      <el-form-item label="生产企业:" :label-width="formLabelWidth">
        <el-input v-model="from.manufacturing" autocomplete="off" />
      </el-form-item>
      <el-form-item label="封面图:" :label-width="formLabelWidth">
              <el-upload
          class="avatar-uploader"
          action="https://localhost:44333/Traceability/UploadFile"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="from.Image" :src="from.Image" class="avatar" style="height: 200px;width: 200px;" />
          <el-icon v-else class="avatar-uploader-icon" style="font-size: 100px;"><PictureFilled /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="from.isno"  type="primary" @click="Modify">
          修改
        </el-button>
        <el-button v-else  type="primary"  @click="AddData">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
    <el-button type="primary" @click="removeall"><el-icon><Delete /></el-icon> &nbsp; 删除 </el-button>
    <div style="margin-top: 20px">
      <el-table :data="datatable" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"  width="55" />
      <el-table-column type="index" width="50" />
      <el-table-column prop="shopName" label="商品名称" width="120" height="30"/>
      <el-table-column prop="batch" label="生产批次" width="120" height="30"/>
      <el-table-column prop="expiration" label="保质期(天)" width="120" height="30"/>
      <el-table-column prop="production_License" label="生产许可证号" width="200" height="30"/>
      <el-table-column prop="manufacturing" label="生产企业" width="300" height="30"/>
      <el-table-column prop="information" label="信息完善度" width="120" height="30"/>
      <el-table-column prop="createByName" label="创建人" width="120" height="30"/>
      <el-table-column prop="createTime" label="创建时间" width="200" height="30"/>
      <el-table-column prop="updateByName" label="修改人" width="120" height="30"/>
      <el-table-column prop="updateTime" label="修改时间" width="120" height="30"/>
      <el-table-column fixed="right" label="操作" min-width="280">
        <template v-slot="scope">
          <el-button link type="primary" @click="GetTraceabilityByIdToDetail(scope.row.indexId)" size="small">
            详情
          </el-button>
          <el-button link type="primary" @click="openModify(scope.row.indexId)" size="small">修改</el-button>
          <el-button link type="primary" @click="ExportTraceOpen" size="small">导出溯源码</el-button>
          <el-button link type="primary" @click="delData(scope.row.indexId)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible"  title="洋神甄选" width="320px" >
    <img :src="imgimg"  style="height: 300px;width: 300px;">
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ExportTraceClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
    </div>
    </el-tab-pane>
  </el-tabs>

  </template>
<script lang="ts" setup>

import {GetTrace} from '@/api/admin/index'
import {type TraceabilityIndexData} from '@/api/admin/type'
import {type delall} from '@/api/admin/type'
import {GetTraceabilityIndexById} from '@/api/admin/index'
import {DelTraceabilityIndexById} from '@/api/admin/index'
import {DelAllTraceabilityIndex} from '@/api/admin/index'
import {ModifyTraceabilityIndexAll} from '@/api/admin/index'

import { Select } from '@element-plus/icons-vue'
import type { TabPaneName } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {AddTraceabilityIndex} from '@/api/admin/index'
import type { UploadProps } from 'element-plus'
import { reactive,onMounted, ref } from 'vue'
import {GetTraceabilityIndex} from '@/api/admin/index'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
const route = useRoute()
const router = useRouter()
const from=reactive<TraceabilityIndexData>({
  indexId:null,
  dialogFormVisible:false,
  shopName:'',
  batch:'',
  expiration:null,
  production_License:'',
  manufacturing:'',
  information:'',
  Image:'',
  createById:null,
  createByName:'' ,
  createTime :'',
  isno:false,
  IsDeleted:false,
  imagess:'',
  
  
})
let tabIndex = 2
const editableTabsValue = ref('2')
const editableTabs = ref([
  {
    title: '溯源管理',
    name: '1',
    content: 'Tab 1 content',
  },
])

const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: 'remove' | 'add'
) => {
  if (action === 'add') {
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
      title: 'New Tab',
      name: newTabName,
      content: 'New Tab content',
    })
    editableTabsValue.value = newTabName
  } else if (action === 'remove') {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  }
}
onMounted(()=>{
    getdata()
})
const datatable=ref([])
const getdata=async()=>{
   await GetTraceabilityIndex().then(function(res){
    console.log(res.data);
    datatable.value=res.data
   })
}
const multipleSelection=ref<delall>()
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
const formLabelWidth = '140px'
const openDialog=()=>{
  from.dialogFormVisible=true;
  from.shopName = "";
        from.batch = "";
        from.expiration = null;
        from.production_License = "";
        from.manufacturing = "";
        from.Image = ""
        from.indexId =null;
        from.createById =null;
        from.createByName = "";
        from.createTime = "";
        from.isno=false
        
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  from.Image = "https://localhost:44333/"+response
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const AddData=async()=>{
        
  await AddTraceabilityIndex(from).then(function(res){
    console.log(res.data);
    if(res.data>0){
      from.dialogFormVisible=false;
     router.push({name:'TraceabilityIndex'})
    }
  })
}
const GetTraceabilityById=async(val:any)=>{
  from.dialogFormVisible=true
    await GetTraceabilityIndexById(val).then(function(res){
        console.log(res.data);
        from.shopName = res.data.shopName;
        from.batch = res.data.batch;
        from.expiration = res.data.expiration;
        from.production_License = res.data.production_License;
        from.manufacturing = res.data.manufacturing;
        from.Image = res.data.image;
        from.indexId =res.data.indexId;
        from.createById = res.data.createById;
        from.createByName = res.data.createByName;
        from.createTime = res.data.createTime;
        from.imagess=res.data.imagess
    })
}

const openModify=async(val1:any)=>{
  from.isno=true
 await GetTraceabilityById(val1) 
 
}
const Modify=async()=>{

  await ModifyTraceabilityIndexAll(from).then(function(res){
    console.log(res.data);
    if(res.data>0){
      from.dialogFormVisible=false
      getdata()
    }
   
  }) 
}
const delData=async(val:any)=>{
   await DelTraceabilityIndexById(val).then(function(res){
    console.log(res.data);
    getdata()
   })
}
const removeall=async()=>{
 var Ids= multipleSelection.value.map(d=>d.indexId)
 console.log(Ids);
  await DelAllTraceabilityIndex(Ids).then(function(res){
    console.log(res.data);
    if(res.data>0){
      getdata()
    }
  })
}
const GetTraceabilityByIdToDetail=(val:any)=>{
  localStorage.setItem("TraceabilityId",val)
  router.push({
    name:"TraceabilityHusbandryDetails",
    query:{
      Id:val
    }
  })
}
const dialogFormVisible = ref(false)

const ExportTraceOpen=()=>{
  dialogFormVisible.value=true;
  ExportTrace()
}
const imgimg=ref("")
const ExportTrace=async()=>{
   await GetTrace().then(function(res){
    console.log(res.data);
    imgimg.value="https://localhost:44333/"+res.data
   })
}
const ExportTraceClose=()=>{
  dialogFormVisible.value=false;
}
</script>